package com.fengyunhe.manager.service.impl;

import com.fengyunhe.manager.dao.AdminUserDao;
import com.fengyunhe.manager.dao.entity.AdminUserEntity;
import com.fengyunhe.manager.service.AdminResetPwdService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 密码重置
 *
 * @author yangyan
 *         Created by Administrator on 2014/11/6.
 */
@Service
public class AdminResetPwdServiceImpl implements AdminResetPwdService {
    @Autowired
    private AdminUserDao adminUserDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> pwdRedis;

    /**
     * 检测用户Email是否存在
     *
     * @param email
     * @return
     */
    @Override
    public String checkUserEmaiAndSetRedis(String email) {
        email = StringUtils.trim(email);
        AdminUserEntity user = this.adminUserDao.getUniqueResultByProperty("email", email);

        if (null == user) {
            return "";
        }
        String uuid = RandomStringUtils.random(12);
        uuid = (uuid + email);
        this.pwdRedis.set(uuid, email, 1800000, TimeUnit.SECONDS);

        return uuid;
    }

    /**
     * Email是否存在
     *
     * @param token
     * @return
     */
    @Override
    public boolean isEmailExists(String token) {
        if (StringUtils.isNotBlank(token)) {
            String email = this.pwdRedis.get(token);
            if (StringUtils.isNotBlank(email)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 密码重置更新
     *
     * @param token
     * @param password
     */
    @Override
    public boolean resetUserPassword(String password, String token) {
        boolean isSuccess = false;
        //获取该充重置密码用户派发的token
        String email = this.pwdRedis.get(token);
        if (StringUtils.isNotBlank(email)) {
            AdminUserEntity userEntity = this.adminUserDao.getUniqueResultByProperty("email", email);

            if (null != userEntity) {
                //对用户新的密码进行加密
                String pwd = email + password + email;
                pwd = DigestUtils.md5Hex(pwd);
                userEntity.setPassword(pwd);

                //更新用户密码
                this.adminUserDao.update(userEntity);
                //移除token.
                this.redisTemplate.delete(token);
                isSuccess = true;
            }
        }
        return isSuccess;
    }
}
